package com.mango.config;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Build;
import android.os.LocaleList;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.webkit.WebSettings;

import com.mango.oaid.DeviceIdentifier;
import com.mango.request.Algorithm;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;
import java.util.Locale;

public final class DeviceConfig {
    static {
        System.loadLibrary("TaobaoUtils");
    }

    private static native String nGetBoot();

    private static native String nGetUpdate();

    private static Application app() {
        return BaseWall.getInstance().getApplication();
    }

    private static Configuration config() {
        return app().getResources().getConfiguration();
    }

    private static DisplayMetrics display() {
        return app().getResources().getDisplayMetrics();
    }

    public static String getImei() {
        return DeviceIdentifier.getIMEI(app());
    }

    public static String getOaid() {
        return DeviceIdentifier.getOAID(app());
    }

    public static String getImeiMd5() {
        return Algorithm.MD5Encrypt(getImei())
                .toLowerCase(Locale.getDefault());
    }

    public static String getOsv() {
        return Build.VERSION.RELEASE;
    }

    public static int getOsc() {
        return Build.VERSION.SDK_INT;
    }

    public static int getScreenType() {
        return config().orientation;
    }

    public static int getDpi() {
        return display().densityDpi;
    }

    public static float getDip() {
        return display().density;
    }

    @SuppressLint("HardwareIds")
    public static String getSerialno() {
        return Build.SERIAL == null ? "" : Build.SERIAL;
    }

    public static String getManufacture() {
        return Build.MANUFACTURER;
    }

    public static String getModel() {
        return Build.MODEL;
    }

    public static String getBrand() {
        return Build.BRAND;
    }

    public static int getDeviceType() {
        return 1;
    }

    public static double getScreenSize() {
        return Math.sqrt(Math.pow(getScreenWidth(), 2)
                + Math.pow(getScreenHeight(), 2)) / (160 * getDip());
    }

    public static String getImsi() {
        String carrier = "";
        TelephonyManager telephonyManager = (TelephonyManager) app().getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA && telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY) {
            carrier = telephonyManager.getNetworkOperator();
        } else if (telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY) {
            carrier = telephonyManager.getSimOperator();
        }
        return carrier;
    }

    public static String getLanguage() {
        Locale locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            locale = LocaleList.getDefault().get(0);
        } else {
            locale = Locale.getDefault();
        }
        return locale.getLanguage() + "-" + locale.getCountry();
    }

    public static JSONObject getPackage(String appID) {
        PackageManager pm = app().getPackageManager();
        JSONObject result = new JSONObject();
        try {
            try {
                result.put("appId", appID)
                        .put("packageName", app().getApplicationInfo().packageName)
                        .put("name", app().getApplicationInfo().loadLabel(pm).toString());

                PackageInfo _package = pm.getPackageInfo(app()
                        .getApplicationInfo().packageName, 0);
                result.put("version", _package.versionName)
                        .put("versionCode",
                                Build.VERSION.SDK_INT >= Build.VERSION_CODES.P
                                        ? _package.getLongVersionCode() : _package.versionCode);
            } catch (Exception exception) {
                result.put("version", "0.0")
                        .put("versionCode", 0);
            }
        } catch (Exception exception) {
            // Do nothing.
        }
        return result;
    }

    public static JSONArray getInstallations() {
        JSONArray array = new JSONArray();
        try {
            PackageManager pm = app().getPackageManager();
            List<ApplicationInfo> allApps = pm.getInstalledApplications(0);
            for (ApplicationInfo ai : allApps) {
                if ((ai.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                    JSONObject pkg = new JSONObject()
                            .put("pkgName", ai.packageName)
                            .put("appName", ai.loadLabel(pm).toString());

                    try {
                        PackageInfo _package = pm.getPackageInfo(ai.packageName, 0);
                        pkg.put("appVersion", _package.versionName)
                                .put("appVersionCode",
                                        Build.VERSION.SDK_INT >= Build.VERSION_CODES.P
                                                ? _package.getLongVersionCode() : _package.versionCode);
                    } catch (Exception exception) {
                        pkg.put("appVersion", "0.0")
                                .put("appVersionCode", 0);
                    }
                    array.put(pkg);
                }
            }
        } catch (Exception e) {
            // Do nothing.
        }
        return array;
    }

    public static int getScreenWidth() {
        return display().widthPixels;
    }

    public static int getScreenHeight() {
        return display().heightPixels;
    }

    public static String getAndroidId() {
        return DeviceIdentifier.getAndroidID(app());
    }

    public static String getAndroidIdMd5() {
        return Algorithm.MD5Encrypt(getAndroidId()).toLowerCase(Locale.getDefault());
    }

    public static String getIncremental() {
        String userAgent;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            try {
                userAgent = WebSettings.getDefaultUserAgent(app());
            } catch (Exception e) {
                userAgent = System.getProperty("http.agent");
            }
        } else {
            userAgent = System.getProperty("http.agent");
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0, length = (userAgent == null
                ? 0 : userAgent.length()); i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    @SuppressLint("HardwareIds")
    public static String getIccid() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            TelephonyManager telephonyManager = (TelephonyManager)
                    app().getSystemService(Context.TELEPHONY_SERVICE);
            try {
                return telephonyManager.getSimSerialNumber();
            } catch (Exception e) {
                // DO nothing.
            }
        }
        return "";
    }

    public static int getScreenBrightness() {
        try {
            return Settings.System.getInt(app()
                    .getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
            return 0;
        }
    }

    public static int getAngle() {
        return 0;
    }

    public static String getHardware() {
        return Build.HARDWARE;
    }

    public static int getBattery() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            BatteryManager manager = (BatteryManager) app().getSystemService(Context.BATTERY_SERVICE);
            return manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        } else {
            try {
                IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
                Intent batteryStatus = app().registerReceiver(null, iFilter);

                int level = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1;
                int scale = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1;

                return (int) (level / (double) scale);
            } catch (Exception exception) {
                return 100;
            }
        }
    }

    public static String getAppStoreVersion() {
        try {
            PackageManager manager = app().getPackageManager();
            ResolveInfo resolve = manager.resolveActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse("market://search?q=pname:com.mango")), PackageManager.MATCH_DEFAULT_ONLY);
            PackageInfo _package = manager.getPackageInfo(resolve.activityInfo.applicationInfo.packageName, 0);

            return _package.packageName + ":" + _package.versionCode;
        } catch (Exception exception) {
            return "";
        }
    }

    public static String getRomVersion() {
        return Build.VERSION.RELEASE;
    }

    public static String getBootMark() {
        return nGetBoot();
    }

    public static String getUpdateMark() {
        return nGetUpdate();
    }
}
